<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<!DOCTYPE html>
<html lang="en" dir="ltr" xmlns:fb="http://ogp.me/ns/fb#">
<head>
<meta charset="utf-8" />

<title>NetSpri</title>
<meta name="description"
	content="Access the desktop camera and video using HTML, JavaScript, and Canvas.  The camera may be controlled using HTML5 and getUserMedia." />
<link type="text/css" rel="stylesheet" media="all"
	href="/netspri/css/style.css" />
<!-- tab选项卡 -->
<link rel="stylesheet" type="text/css" href="/netspri/css/demo.css" />
<link rel="stylesheet" type="text/css" href="/netspri/css/tabs.css" />
<link rel="stylesheet" type="text/css" href="/netspri/css/tabstyles.css" />

<style type="text/css">
	.tablm {
		width: 1240 px;
		height: 400px;
		margin: 0px auto
	}

	#start,#ready,#reset,#upload,#save {
		width: 140px;
		background-color: #87CEFA;
	}


	#start:HOVER,#ready:hover,#reset:hover,#upload:hover,#save:hover {
	 	background-color: #FF7F00;
	}




	.saveButton{
		padding-left: 180px;
		padding-top: 30px;
		margin-bottom: 10px;
	}

	html,body {
		height: 100%;
		width: 100%;
	}
</style>

<script type="text/javascript" src="/netspri/js/jquery-2.2.3.js"></script>
<!-- 图表插件 -->
<script type="text/javascript" src="/netspri/js/highcharts.js"></script>


</head>

<body>
	<header id=top>
		<div class="center clear">
			<div class=header-title>
				<a href="/netspri/user/home" class=logo><span style="font-family: cursive;font-weight: bold;">SPRi 传感网络平台</span> </a>
			</div>


			<div class=header-sda
				style='font-family:cursive; top:20px;text-align:right;right: 150px'>
				<a href="/netspri/user/home" style=display:block;text-decoration:none; rel=nofollow>
					<span class=header-sda-byline
					style="display:block;text-transform:uppercase;color:yellow;font-size:80%;font-weight:bold;line-height:1;">
						fo-spri </span>
				<!--  <span class=header-sda-headline
					style="display:block;color: #fff;font-weight: bold; font-size:80%;">
						Low-cost, Portable, Easy to use<br>Point of Care Testing
				</span> --> <span class=header-sda-secondary
					style="display:block;font-size: 80%;color: #91c661;line-height:1;">
						Make detection easier!</span>
				</a>
			</div>
		</div>

	</header>

	<section>
		<div class="tabs tabs-style-linetriangle">
			<nav>
				<ul>
					<li><a href="#section-linetriangle-1"><span>Real-timeImage</span></a></li>
					<li><a href="#section-linetriangle-2"><span>ResponseCurve</span></a></li>
				</ul>
			</nav>
			<div class="content-wrap">


				<section id="section-shape-1">

					<!-- content wrapper -->


					<!-- main content column -->
					<!--CONTENT-->

					<p></p>
					<table class="tablm">

						<tr>
							<td align="center">Video of Detection Area</td>
							<td><button id="start" autofocus="autofocus">Start</button></td>
							<td align="center">SnappedImage&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input id="result"
								type="text" size="6" readonly="readonly" style="color: blue; ;">
							</td>
						</tr>


						<tr>
							<td><video id="video" width="480" height="360" controls></video>
							</td>
							<td></td>
							<td>
								<canvas id="canvas" width="480" height="360"></canvas>
							</td>
						</tr>
					</table>


					<script>
						// Put event listeners into place
						var series;
						var datalist=new Array();
						var avg = 0;
						var saveFlag= false;
						var init= false;
						/* $(function() {
							$(document)
									.ready( */
											
											//初始化图表插件
											function dojob( startY) {
												//时区
											Highcharts.setOptions({global : {useUTC : false}});
												
												//清空datalist
												datalist=[];
												
												$('#container').highcharts(
																{chart : {
																		type : 'spline',
																		animation : Highcharts.svg, // don't animate in old IE               
																		marginRight : 10,
																		events : {
																			load : function() {

																				// set up the updating of the chart each second             
																				series = this.series[0];
																				/* setInterval(
																						function() {
																							var x = (new Date())
																									.getTime(), // current time         
																							y = Math
																									.random()*100;
																							series
																									.addPoint(
																											[
																													x,
																													y ],
																											true,
																											true);
																						},
																						3000); */
																			}
																		}
																	},
																	title : {text : '实时响应曲线'},
																	xAxis : {
																		type : 'datetime',
																		tickPixelInterval : 100
																	},
																	yAxis : {title : {text : '响应值'},
																		
																		plotLines : [ {
																			value : 0,
																			width : 1,
																			color : '#808080'
																		} ]
																	},
																	
																	tooltip : {
																		formatter : function() {
																			return '<b>'
																					+ this.series.name
																					+ '</b><br/>'
																					+ Highcharts.numberFormat(this.y,3);
																		}
																	},
																	legend : {
																		enabled : false
																	},
																	exporting : {
																		enabled : true
																	},
																	//初始化图表
																	series : [ {
																		name : '响应值',
																		data : (function() {
																			// generate an array of random data                             
																			var data = [], time = (new Date()).getTime(), i;

																			for (i = -99; i <= 0; i++) {
																				data.push({
																							x : time+ i* 3000,
																							y:startY
																						});
																			}
																			return data;
																		})()
																	} ]
																});
											};

						
						//视频流和图像数据获取
						window.addEventListener(
										"DOMContentLoaded",
										function() {
											// Grab elements, create settings, etc.
											var canvas = document.getElementById("canvas"), 
											context = canvas.getContext("2d"),
											video = document.getElementById("video"), 
											videoObj = {"video" : true}, 
											errBack = function(error) {
												console.log(
																"Video capture error: ",
																error.code);
											};

											// Put video listeners into place
											if (navigator.getUserMedia) { // Standard
												navigator.getUserMedia(
														videoObj, 
														function(stream) {
															video.src = stream;
															video.play();
														}, errBack);
											} else if (navigator.webkitGetUserMedia) { // WebKit-prefixed
												navigator.webkitGetUserMedia(videoObj,
																function(stream) {
																	video.src = window.URL.createObjectURL(stream);
																	video.play();}, errBack);
											} else if (navigator.mozGetUserMedia) { // WebKit-prefixed
												navigator.mozGetUserMedia(videoObj,
																function(stream) {
																	video.src = window.URL.createObjectURL(stream);
																	video.play();
																}, errBack);
											}

											// Trigger photo take
											
											//图像处理方法
											function snapImage() {
												var sum = 0;
												context.drawImage(video, 0, 0, 480, 360);

												var imgData = context.getImageData(0, 0, 480, 360);
												
												for (var i = 0; i < imgData.data.length; i += 4) {
													sum += imgData.data[i];
													/*  imgData.data[i+1]=0;
													 imgData.data[i+2]=0; */
												}
												avg = sum / 480 / 360;
												
												//保留3位小数
												avg=avg.toFixed(3);
												/* 	context.putImageData(imgData,0,0); */
												/* alert(avg); */
												
												//显示在result文本框
												$("#result").val(avg);
												var x = (new Date()).getTime();
												
												if (saveFlag) {
													series.addPoint([ x, avg * 1 ], true, true);
													//将数据存入datalist
													datalist.push(avg * 1);
												}
												;
											}

											var clickTime = 1;
											var interval = null;
											$("#start").click(
															function() {
																clickTime++;

																if (clickTime % 2 == 0) {
																	$("#start").text("Pause");
																	$("#start").css('background', '#FF7F00');
																	
																	//抓取图片，计算灰度均值
																	snapImage();

																	interval = setInterval(snapImage, 3000);
																} else {
																	if (interval != null) {
																		$("#start").text("Start");
																		$("#start").css('background', '#87CEFA');
																		window.clearInterval(interval);
																	}
																}
															});
										});
					</script>



				</section>
				<section id="section-shape-2">
				<table  >
					<tr>
						<td>
					<div class="saveButton">
						<button id="save" >Ready</button>
					</div>
						</td>
						<td>
					<div class="saveButton">
						<button id="reset" >Reset</button>
					</div>
						</td>
						<td>
					<div class="saveButton">
						<button id="upload" >Upload</button>
					</div>
					
				
						</td>
					</tr>
				</table>
	<div id="container" style="width:900px;height:420px;margin:0 auto;"></div>
				</section>

			</div>
			<!-- /content -->
		</div>
		<!-- /tabs -->
	</section>

	<script src="/netspri/js/cbpFWTabs.js"></script>
	<script>
	
		//选项卡插件
		(function() {

			[].slice.call(document.querySelectorAll('.tabs')).forEach(
					function(el) {
						new CBPFWTabs(el);
					});

		})();
		
		$("#save").click(function(){
			
			//初始化
			if (!init) {
				dojob(avg * 1);
				init = true;
			};
			
			//更改标记的状态，当saveflag标记为true时，将计算出的像素均值添加到图表显示并且记录到listdata中
			if (!saveFlag) {
				saveFlag = true;
				$("#save").text("Running");
				$("#save").css('background', '#FF7F00');
			} else {
				saveFlag = false;
				$("#save").text("Ready");
				$("#save").css('background', '#87CEFA');
			}

			/* setInterval(
					function() {
						var x = (new Date())
								.getTime(), // current time         
						y = Math
								.random()*100;
						series
								.addPoint(
										[
												x,
												y ],
										true,
										true);
					},
					3000); */
		});
		
		//上传检测数据
		$("#upload").click(function() {

			if (datalist.length != 0) {
				var confup = window.confirm("上传到数据库?");

				if (confup) {
					//把datalist数组转为JSON格式字符串
					var jsondata = JSON.stringify(datalist);

					$.post("/netspri/detection/singlechannel/upload", 
					{
						uploaddata : jsondata,
						id : ${User.user_id}
					}, 
					function(data) {
						if (data) {
							var c = window.confirm("已成功上传数据库，是否初始化图表？");
							if (c) {
								dojob(avg * 1);
							};
						} else {
							alert("上传失败!");
						}
					});
				};
			};
		});

		$("#reset").click(function() {
			var c = window.confirm("确认重置？");
			if (c) {
				dojob(avg * 1);
			}
		});
	</script>

</body>
</html>
